package account

import (
	"github.com/gin-gonic/gin"
	"mercury/session"
	"net/http"
	"time"
)

func processRequest(cxt gin.Context) {
	var userSession session.Session
	var err error
	defer func() {
		if userSession == nil {
			userSession, _ = session.CreateSession()
		}
		cxt.Set(MercurySession, userSession)
	}()
	cookie, err := cxt.Request.Cookie(CookieSessionId)
	if err != nil {
		cxt.Set(MercuryUserId, int64(0))
		cxt.Set(MercuryUserLoginStatus, int64(0))
		return
	}
	sessionId := cookie.Value
	if len(sessionId) == 0 {
		cxt.Set(MercuryUserId, int64(0))
		cxt.Set(MercuryUserLoginStatus, int64(0))
		return
	}
	userSession, err = session.GetSession(sessionId)
	if err != nil {
		cxt.Set(MercuryUserId, int64(0))
		cxt.Set(MercuryUserLoginStatus, int64(0))
		return
	}
	tmpUserId, err := userSession.Get(MercuryUserId)
	if err != nil {
		cxt.Set(MercuryUserId, int64(0))
		cxt.Set(MercuryUserLoginStatus, int64(0))
		return
	}
	userId, ok := tmpUserId.(int64)
	if !ok || userId == 0 {
		cxt.Set(MercuryUserId, int64(0))
		cxt.Set(MercuryUserLoginStatus, int64(0))
		return
	}
	cxt.Set(MercuryUserId, userId)
	cxt.Set(MercuryUserLoginStatus, 1)
	return
}

func processResponse(cxt *gin.Context) {
	var userSession session.Session
	tmpUserSession, ok := cxt.Get(MercurySession)
	if !ok {
		return
	}
	userSession, ok = tmpUserSession.(session.Session)
	if !ok {
		return
	}
	if !userSession.IsModify() {
		return
	}
	err := userSession.Save()
	if err != nil {
		return
	}
	sessionId := userSession.GetId()
	cookie := &http.Cookie{
		Name:       CookieSessionId,
		Value:      sessionId,
		Path:       "/",
		Domain:     "",
		Expires:    time.Time{},
		RawExpires: "",
		MaxAge:     CookieMaxAge,
		Secure:     false,
		HttpOnly:   true,
		SameSite:   0,
		Raw:        "",
		Unparsed:   nil,
	}
	http.SetCookie(cxt.Writer, cookie)
}

func GetUserId(ctx *gin.Context) (userId int64, err error) {
	tmpUserId, ok := ctx.Get(MercuryUserId)
	if !ok {
		err = ErrorUserIdNotExist
		return
	}
	userId, ok = tmpUserId.(int64)
	if !ok {
		err = ErrorUserIdNotExist
	}
	return
}

func IsLogin(ctx *gin.Context) bool {
	tmpLoginStatus, ok := ctx.Get(MercuryUserLoginStatus)
	if !ok {
		return false
	}
	loginStatus, ok := tmpLoginStatus.(int64)
	if !ok {
		return false
	}
	return loginStatus == 1
}
